﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WpfApp_SmartParking_Entities;
using WpfApp_SmartParking_IService;

namespace WpfApp_SmartParking.ViewModels;

public class LoginViewModel : BindableBase, IDialogAware
{
    public string Title => "用户登录";

    public event Action<IDialogResult>? RequestClose;

    public DelegateCommand? LoginCommand { get; set; }

    private IUserService _userService;


    private string? _userName;

    public string? UserName
    {
        get { return _userName; }
        set { SetProperty<string?>(ref _userName, value); }
    }

    private string?  _passWord;

    public string?  PassWord
    {
        get { return _passWord; }
        set { SetProperty<string?>(ref _passWord, value); }
    }

    private bool _isRecordPassword;

    public bool IsRecordPassword
    {
        get { return _isRecordPassword; }
        set { SetProperty<bool>(ref _isRecordPassword, value); }
    }

    private string? _errorMessage;

    public string? ErrorMessage
    {
        get { return _errorMessage; }
        set { SetProperty<string?>(ref _errorMessage, value); }
    }

    private bool _isLoading;

    public bool IsLoading
    {
        get { return _isLoading; }
        set { SetProperty<bool>(ref _isLoading, value); }
    }



    public bool CanCloseDialog()
    {
        return true;
    }

    public void OnDialogClosed()
    {

    }

    public void OnDialogOpened(IDialogParameters parameters)
    {

    }

    public LoginViewModel(IUserService userService)
    {
        this.UserName = "admin";
        this.PassWord = "a";
        LoginCommand = new DelegateCommand(DoLogin);
        _userService = userService;
    }

    /// <summary>
    /// 登录
    /// </summary>
    private async void DoLogin()
    {
        this.ErrorMessage = "";
        if (string.IsNullOrEmpty(this.UserName)) 
        {
            this.ErrorMessage = "请输入用户名！";
            return;
        }
        if (string.IsNullOrEmpty(this.PassWord))
        {
            this.ErrorMessage = "请输入密码！";
            return;
        }
        this.IsLoading = false;
        //模拟等待两秒
        //await Task.Run(async () => 
        //{
        //    await Task.Delay(2000);
        //});
        SysUser? sysUser = this._userService.Login(this.UserName, this.PassWord);
        this.IsLoading = false;
        if (sysUser == null)
        {
            this.ErrorMessage = "用户名或密码错误！";
            return;
        }
        Application.Current.Dispatcher.Invoke(() => 
        {
            DialogParameters param = new DialogParameters();
            param.Add("user",sysUser);
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK, param));
        });
        
    }
}
